import Vue from 'vue'
import store from '@/store'
// 当打包构建应用时，JavaScript 包会变得非常大，影响页面加载。
// 如果我们能把不同路由对应的组件分割成不同的代码块，然后当路由被访问的时候才加载对应组件，这样就更加高效了。
const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const NotFind = () => import('@/views/404')
const Home = () => import('@/views/layout/Home')
const QA = () => import('@/views/layout/QA')
const Video = () => import('@/views/layout/Video')
const User = () => import('@/views/layout/User')
const Search = () => import('@/views/Search')
const userEdit = () => import('@/views/layout/User/edit')
const Result = () => import('@/views/Search/result')
import VueRouter from 'vue-router'
const Article = () => import('@/views/article')
const Chat = () => import('@/views/layout/User/chat')

// 把router的push的方法的错误  。catch方法捕获  （NavigationDuplicated， 没有让它报出来
// router.push('./login')能解决 via a navigation guard.）
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,

    children: [
      {
        path: '',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: 'QA',
        component: QA

      },

      {
        path: 'user',
        component: User
        // meta: {
        //   isKeepAlive: true
        // }
      },
      {
        path: 'video',
        component: Video
        // meta: {
        //   isKeepAlive: true
        // }
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/user/edit',
    component: userEdit
  },
  {
    path: '/article/:id',
    component: Article
  },
  {
    path: '*',
    component: NotFind
  }
]

const router = new VueRouter({
  routes
})
// 1.判断是否有token 有token next（）
//                   没有token 判断to  是 /login /home  next()
//                                    是 /user /edit next(/Login)

const loginUrls = ['/user', '/user/edit', '/user/chat']
router.beforeEach((to, from, next) => {
  if (store.state.user.token.token) {
    next()
    return
  }

  // 需求：登录回跳，
  //     用户如果 直接访问home a.然后点击user页会被拦截到 login页
  //                           此时登录时应该返回到user页面
  //                         b ,如果没有拦截用返回一个默认值

  if (loginUrls.includes(to.path)) {
    console.log(to.path)
    // next('/login')
    router.push({
      path: './login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})

export default router
